<template>
  <VPage v-loading="loadings.download">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <div class="w-full">
          <el-tabs v-model="activeName" @tab-change="handleChange">
            <el-tab-pane
              :label="item.platform_name"
              :name="item.platform_code"
              v-for="(item, index) in platformOptions"
              :key="index"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <el-select
          v-model="form.shop_id"
          class="!w-[160px]"
          placeholder="店铺"
          multiple
          collapse-tags
          filterable
        >
          <el-option
            v-for="item in shopOptions"
            :key="item.shop_id"
            :label="item.shop_name"
            :value="item.shop_id"
          ></el-option>
        </el-select>
        <VGroup>
          <el-select class="selectClass !w-[115px]" v-model="form.timeRange.type">
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="form.timeRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="max-width: 300px"
            :default-time="defaultTime()"
          />
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[115px]" v-model="form.personRange.type">
            <el-option
              v-for="item in personOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <select-personnel
            class="w-40"
            v-model="form.personRange.value"
            :multiple="true"
            placeholder="请选择"
          ></select-personnel>
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.skuRange.type">
            <el-option
              v-for="item in skuOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <multi-input
            v-model="form.skuRange.value"
            placeholder="批量搜索，一行一个"
            class="w-50"
          ></multi-input>
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[120px]" v-model="form.channelRange.type">
            <el-option
              v-for="item in channelOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <multi-input
            v-model="form.channelRange.value"
            placeholder="批量搜索，一行一个"
            class="w-50"
          ></multi-input>
        </VGroup>
        <el-select class="!w-[120px]" placeholder="状态" v-model="form.status" clearable>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          class="!w-[170px]"
          v-if="activeName == 'amazon'"
          placeholder="是否同步Listing标题"
          v-model="form.is_sync_title"
          clearable
        >
          <el-option
            v-for="item in isSyncOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </template>
      <template #form_handle>
        <el-button type="primary" @click="query()">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </template>
      <template #toolbar_btns>
        <VButton
          auth="/goods/goods-management/channel-sku/relevant"
          type="primary"
          @click="relevant()"
          >关联渠道SKU</VButton
        >

        <VButton
          auth="/goods/goods-management/channel-sku/relevant"
          @click="batchrelevant()"
          >批量关联渠道SKU
        </VButton>
        <VButton
          auth="/goods/goods-management/channel-sku/batch-change-user"
          @click="batchChangeUser(1)"
          >批量修改销售人员
        </VButton>
        <VButton
          auth="/goods/goods-management/channel-sku/batch-change-operation-user"
          @click="batchChangeUser(2)"
          >批量修改操作运营人员</VButton
        >
        <VButton
          auth="/goods/goods-management/channel-sku/change-sku"
          @click="handleChangeSKU()"
          v-if="activeName === 'amazon'"
          >SKU换标
        </VButton>
        <VButton
          auth="/goods/goods-management/channel-sku/download-tag"
          @click="handleDownloadTag()"
          v-if="activeName === 'amazon'"
          >FNSKU标签下载
        </VButton>

        <VButton
          auth="/goods/goods-management/channel-sku/enable"
          :loading="loadings.enable"
          @click="handleStatus('Enable')"
        >
          <svg-icon class="mr-1 base-text-color" icon-class="state_finish_enable" />
          启用
        </VButton>
        <VButton
          auth="/goods/goods-management/channel-sku/disabled"
          :loading="loadings.disable"
          @click="handleStatus('Disable')"
        >
          <svg-icon class="mr-1 text-red-500" icon-class="state_finish_cover" />禁用
        </VButton>

        <VButton
          auth="/goods/goods-management/channel-sku/import"
          plain
          class="ml-auto"
          @click="importFile"
          ><i class="dk-iconfont icon-Download" />导入</VButton
        >
        <VButton
          auth="/goods/goods-management/channel-sku/export"
          plain
          @click="handleExport"
          ><i class="dk-iconfont icon-Upload" />导出</VButton
        >
      </template>
    </VTable>
  </VPage>
  <RelevanceChannel
    ref="relevantRef"
    :shopOptions="shopOptions"
    @query="query"
  ></RelevanceChannel>
  <ImportChannel ref="importRef" @query="query"></ImportChannel>
  <batchRelevanceChannel
    ref="batchRelevanceChannelRef"
    :shopOptions="shopOptions"
    :platformOptions="platformOptions"
  >
  </batchRelevanceChannel>
  <VLog
    ref="logRef"
    class="dialogPublic"
    :api="productChannelSKULog"
    options="channel_id"
    :isSearch="true"
  ></VLog>
  <changeSKU ref="changeSKURef"></changeSKU>
  <batchSetOperationUser
    ref="batchSetOperationUserRef"
    @refresh="query"
  ></batchSetOperationUser>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <div id="barcode" class="w-[240px] h-[170px]"></div>
</template>
<script setup name="Goods-managementChannel-sku" lang="jsx">
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { nextTick, ref, reactive, toRefs, onMounted } from "vue";
import { queryChannelSkuList, channelSkuUpdateStatus, productChannelSKULog } from "./api";
import { getShop } from "@/api/index";
import RelevanceChannel from "./components/RelevanceChannel";
import ImportChannel from "./components/ImportChannel";
import batchRelevanceChannel from "./components/batchRelevanceChannel";
import VLog from "@/components/VLog";
import changeSKU from "./components/changeSKU";
import batchSetOperationUser from "./components/batchSetOperationUser";
import DerivedCenter from "@/components/DerivedCenter";
import {
  statusOptions,
  isSyncOptions,
  personOption,
  skuOption,
  channelOption,
  timeOptions,
} from "./data.js";
import JsBarcode from "jsbarcode";
import JSZip from "jszip";
import html2pdf from "html2pdf.js";

import useCommonStore from "@/store/modules/common";
const commonStore = useCommonStore();
const platformOptions = computed(() => {
  if (!commonStore.platformOptions) {
    commonStore.getPlatformList();
  }
  let options = commonStore.platformOptions.filter((i) => {
    if (
      (window.BTN_AUTH || []).includes(
        `/goods/goods-management/channel-sku/${i.platform_code}`
      )
    ) {
      return i;
    }
  });
  if (!data.isInitialized && options.length > 0) {
    activeName.value = options[0]?.platform_code;
    platform_id.value = options[0]?.platform_id;
    getShopList();
    data.isInitialized = true;
  }
  return options;
});

const data = reactive({
  activeName: "",
  platform_id: "",
  loadings: {
    download: false,
  },
  shopOptions: [],
  isInitialized: false,
});
const { activeName, loadings, shopOptions, platform_id, isInitialized } = toRefs(data);

const tableRef = ref();

const tableOptins = reactive({
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      shop_id: "",
      status: "",
      operations_personnel: "",
      skuRange: { type: "goods_sku", value: [], range: false },
      timeRange: { type: "create_time", value: [], range: true },
      channelRange: { type: "platform_sku", value: [], range: false },
      personRange: { type: "operations_id", value: [], range: false },
      platform: "",
    },
  },
  columns: [
    { type: "checkbox", width: "40" },
    {
      field: "site",
      title: "站点",
      width: "100",
    },
    {
      field: "shop_name",
      title: "店铺",
      width: "200",
    },
    {
      field: "product_name",
      title: "商品名称",
      width: "240",
    },
    {
      field: "product_en_name",
      title: "平台产品标题",
      width: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                {row.is_sync_title == 1 ? (
                  <el-tooltip
                    effect="dark"
                    content="已停止同步Listing平台标题！！"
                    placement="top-start"
                  >
                    <svg-icon
                      class="base-red-color text-lg"
                      icon-class="hint_cover2"
                    ></svg-icon>
                  </el-tooltip>
                ) : (
                  ""
                )}
              </div>
              <vText value={row.product_en_name}></vText>
            </div>
          );
        },
      },
    },
    {
      field: "asin",
      title: "ASIN",
      width: "120",
    },
    {
      field: "platform_sku",
      title: "渠道SKU",
      width: "140",
      sortable: true,
    },
    {
      field: "fn_sku",
      title: "FNSKU",
      width: "140",
    },
    {
      field: "is_default_channel_sku",
      title: "是否默认渠道SKU",
      width: "140",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row.is_default_channel_sku ? "是" : "否"}</div>
            </div>
          );
        },
      },
    },
    {
      field: "spu",
      title: "SPU",
      width: "120",
    },
    {
      field: "sku",
      title: "系统SKU/自定义SKU",
      width: "180",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row.goods_sku}</div>
              <div>{row.custom_sku}</div>
            </div>
          );
        },
      },
    },
    {
      field: "UPCEAN",
      title: "UPC/EAN",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.upc && row.ean ? (
                <span class="text-gray-600" underline={false}>
                  {row.upc}/{row.ean}
                </span>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
    {
      field: "operator",
      title: "状态",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.status == 0 ? (
                <div class="flex items-center">
                  <svg-icon
                    class="mr-1 base-text-color"
                    icon-class="state_finish_enable"
                  />
                  启用
                </div>
              ) : (
                <div class="flex items-center">
                  <svg-icon class="mr-1 text-red-500" icon-class="state_finish_cover" />
                  禁用
                </div>
              )}
            </div>
          );
        },
      },
    },
    {
      field: "operator_user_id_text",
      width: "140",
      title: "操作运营人员",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              操作运营人员
              {activeName.value == "amazon" ? (
                <el-tooltip
                  placement="top"
                  content="销售人员：负责某个ASIN的主要运营和管理。销售人员拥有该ASIN的操作权限，且该ASIN产生的利润会计入该运营人员的业绩中。<br/>（对应信诚ERP Amazon listing中的销售人员）  <br/>操作运营人员：协助销售人员进行ASIN管理。操作运营拥有操作权限，但该ASIN产生的利润不会计入操作运营的业绩中。<br/>（操作运营需与销售预测表中的销售人员保持一致）  <br/>举例说明：<br/>假设ASIN A的销售人员是张三，她负责ASIN A的管理工作，且该ASIN A产生的利润会计入张三的业绩中。<br/>如果ASIN A的管理过程中需要李四协助处理建单发货等工作，<br/>那么李四可以作为操作运营被添加到系统中协助操作，但李四不会参与ASIN A的利润分配。"
                  raw-content
                >
                  <svg-icon icon-class="hint_cover2"></svg-icon>
                </el-tooltip>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
    {
      field: "operations_personnel_text",
      width: "180",
      title: "销售人员",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              销售人员
              {activeName.value == "amazon" && (
                <el-tooltip
                  placement="top"
                  content="销售人员：负责某个ASIN的主要运营和管理。销售人员拥有该ASIN的操作权限，且该ASIN产生的利润会计入该运营人员的业绩中。<br/>（对应信诚ERP Amazon listing中的销售人员）  <br/>操作运营人员：协助销售人员进行ASIN管理。操作运营拥有操作权限，但该ASIN产生的利润不会计入操作运营的业绩中。<br/>（操作运营需与销售预测表中的销售人员保持一致）  <br/>举例说明：<br/>假设ASIN A的销售人员是张三，她负责ASIN A的管理工作，且该ASIN A产生的利润会计入张三的业绩中。<br/>如果ASIN A的管理过程中需要李四协助处理建单发货等工作，<br/>那么李四可以作为操作运营被添加到系统中协助操作，但李四不会参与ASIN A的利润分配。"
                  raw-content
                >
                  <svg-icon icon-class="hint_cover2"></svg-icon>
                </el-tooltip>
              )}
            </div>
          );
        },
      },
    },
    {
      field: "operations_personnel",
      width: "180",
      title: "开发人员",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text-[#333333]">
                {row.goods_sku_info?.developer_text || "--"}
              </div>
            </div>
          );
        },
      },
    },
    {
      field: "create_user",
      title: "创建人",
      width: "180",
      sortable: true,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="text=[#333333]">{row.create_user_text}</div>
              <div class="text-xs text-[#666666]">{row.create_time}</div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: "120",
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="table-option">
              <div>
                {row.status == 0 ? (
                  <VButton
                    auth="/goods/goods-management/channel-sku/edit"
                    type="primary"
                    link
                    class="border-right"
                    onClick={() => relevant(row)}
                  >
                    编辑
                  </VButton>
                ) : (
                  ""
                )}

                <el-button type="primary" link onClick={() => viewLog(row.id)}>
                  日志
                </el-button>
              </div>
            </div>
          );
        },
      },
    },
  ],

  proxyConfig: {
    seq: true,
    sort: true,
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: async ({ page, form, sort }) => {
        const formData = {
          ...form,
          platform: activeName.value,
        };
        const res = await queryChannelSkuList({ ...formData, ...page, sort });
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total,
          });
        });
      },
    },
  },
});

const handleChange = (platform) => {
  const item = platformOptions.value.find((i) => i.platform_code == platform) || {};
  platform_id.value = item.platform_id;
  getShopList();
  tableRef.value.setForm({
    platform,
    is_sync_title: "",
  });
  console.log(activeName.value);
  refresh();
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};

const handleStatus = async (status) => {
  const records = getSelectRow();
  if (records.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  const ids = records.map((i) => i.id);
  try {
    const res = await channelSkuUpdateStatus({
      status,
      ids,
    });
    ElMessage.success(res.message);
    nextTick(() => {
      tableRef.value.query();
    });
  } catch (e) {
    throw Error(e);
  }
};

// 导出
const DerivedCenterRef = ref();
const handleExport = () => {
  const records = getSelectRow().map((i) => {
    return i.id;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.ids = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
    condition.platform = activeName.value;
  }

  DerivedCenterRef.value.open({
    tag_name: "goods_product_channel_sku",
    condition,
  });
};

const relevantRef = ref();
// 关联渠道sku
const relevant = (item) => {
  console.log("activeName.value");
  console.log(activeName.value);

  nextTick(() => {
    if (item) {
      relevantRef.value.open(Object.assign({}, item));
    } else {
      relevantRef.value.open(null, activeName.value);
    }
  });
};

// 导入
const importRef = ref();
const importFile = () => {
  nextTick(() => {
    importRef.value.open(activeName.value);
  });
};

const query = () => {
  tableRef.value.query();
};

const resetForm = () => {
  activeName.value = platformOptions.value[0]?.platform_code;
  nextTick(() => {
    tableRef.value.resetAndQuery();
  });
};

const getShopList = async () => {
  try {
    const res = await getShop({
      platform_ids: [platform_id.value],
    });
    shopOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

onMounted(() => {
  // getShopList();
});

// 批量关联渠道sku
const batchRelevanceChannelRef = ref();
const batchrelevant = () => {
  batchRelevanceChannelRef.value.open(activeName.value);
};

//查看日志
const logRef = ref();
const viewLog = (id) => {
  logRef.value.open(id);
};

// 更换SKU
const changeSKURef = ref();
const handleChangeSKU = () => {
  const records = getSelectRow();
  if (records.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  const ids = records.filter((i) => i.fn_sku && i.asin).map((i) => i.id);
  if (ids.length == 0) {
    ElMessage.error("选择的FNSKU或ASIN都为空,请重新选择");
    return;
  }

  if (ids.length != records.length) {
    ElMessage.warning("选择的项FNSKU或ASIN有些为空,已进行过滤");
  }
  changeSKURef.value.open(ids);
};

// 批量修改运营人员
const batchSetOperationUserRef = ref();
const batchChangeUser = (type) => {
  const ids = getSelectRow().map((i) => i.id);
  if (ids.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }
  batchSetOperationUserRef.value.open(ids, type);
};

const handleDownloadTag = async () => {
  const records = getSelectRow();
  if (records.length == 0) {
    ElMessage.error("至少选择一项");
    return;
  }

  const data = records.filter((i) => i.fn_sku);
  if (data.length == 0) {
    ElMessage.error("选择的FNSKU为空,请重新选择");
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  const zip = new JSZip(); // 创建一个新的 Zip 实例
  for (let index = 0; index < data.length; index++) {
    let element = createCode(data[index]);
    await downloadPDF(element, index, data[index], zip);
  }

  zip.generateAsync({ type: "blob" }).then(function (content) {
    saveAs(content, "FNSKU标签.zip");
    loading.close();
  });
};

const downloadPDF = async (element, index, row, zip) => {
  let filename = row.fn_sku + "+" + row.goods_sku;

  const opt = {
    margin: 1,
    filename,
    image: { type: "jpeg", quality: 1 },
    html2canvas: { scale: 10, useCORS: true },
    jsPDF: {
      unit: "mm",
      format: [70, 50],
      orientation: "landscape",
    },
  };
  const canvas = html2pdf().from(element).set(opt).output("blob");
  zip.file(`${filename}.pdf`, canvas);
};

const createCode = (row) => {
  const uniqueId = `barcode_${row.goods_sku}`;
  const svgElement = document.createElement("svg");
  svgElement.id = uniqueId;
  const container = document.getElementById("barcode");
  const svg_div = document.createElement("div");
  svg_div.style.display = "flex";
  svg_div.style.justifyContent = "center";
  svg_div.style.width = "100%";

  if (!container) {
    console.error(`Container with ID barcode not found`);
    return null;
  }
  container.innerHTML = "";
  svg_div.appendChild(svgElement);
  container.appendChild(svg_div);

  try {
    JsBarcode(`#${uniqueId}`, row.fn_sku, {
      format: "CODE128",
      width: 1.6,
      displayValue: true,
      height: 40,
      margin: 5,
    });
    const sku_en_title = document.createElement("div");
    sku_en_title.style.wordBreak = "break-all";
    sku_en_title.style.fontSize = "12px";
    const title = row.product_en_name;
    if (!title || title?.length <= 45) {
      sku_en_title.textContent = title;
    } else {
      sku_en_title.textContent = title.slice(0, 45) + "...";
    }

    container.appendChild(sku_en_title);
    const div_info = document.createElement("div");
    div_info.style.display = "flex";
    div_info.style.justifyContent = "space-between";
    div_info.style.width = "100%";
    const new_info = document.createElement("div");
    new_info.style.fontSize = "12px";
    new_info.textContent = "NEW";
    div_info.appendChild(new_info);
    const sku_info = document.createElement("div");
    sku_info.style.fontSize = "12px";
    sku_info.textContent = row.goods_sku_info.sku;
    div_info.appendChild(sku_info);
    container.appendChild(div_info);
    const tips = document.createElement("div");
    tips.style.fontSize = "12px";
    tips.style.marginTop = "6px";
    tips.textContent = "Made In China";
    container.appendChild(tips);
  } catch (error) {
    console.error("Failed to generate barcode:", error);
    return null;
  }

  return container.outerHTML;
};
</script>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

.form-item-bgColor {
  background-color: #fafafa !important;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.vx-table__form-content) {
  padding-top: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}
</style>
